package io.karim.materialtabs.sample;

import io.karim.MaterialTabs;
import io.karim.materialtabs.sample.dialog.ConstandCodes;
import io.karim.materialtabs.sample.dialog.CustomDialog;
import io.karim.materialtabs.sample.widget.ActionBar;
import ohos.aafwk.ability.Ability;
import ohos.aafwk.content.Intent;
import ohos.aafwk.content.Operation;
import ohos.agp.components.AttrHelper;
import ohos.agp.components.PageSlider;
import ohos.agp.components.Text;
import ohos.agp.text.RichText;
import ohos.agp.text.RichTextBuilder;
import ohos.agp.text.TextForm;
import ohos.agp.utils.Color;
import ohos.global.resource.NotExistException;
import ohos.global.resource.WrongTypeException;
import ohos.utils.net.Uri;

import java.io.IOException;
import java.util.ArrayList;

/**
 * MainAbility
 *
 * @since 2021/07/23
 */
public class MainAbility extends Ability {
    /**
     * Intent used to start {@link MainAbility}.
     */
    public Intent startTabsAbilityIntent;
    /**
     * Holds references to fragments from the time they are attached to Ability until they are dettached.
     */
    private final ArrayList<ResettableFragment> mFragments = new ArrayList<>();

    @Override
    public void onStart(Intent intent) {
        initStatus(this);
        super.onStart(intent);
        super.setUIContent(ResourceTable.Layout_ability_main);
        initView();
    }

    private void initView() {
        startTabsAbilityIntent = new Intent();
        Operation operation = new Intent.OperationBuilder()
                .withBundleName("io.karim.materialtabs.sample")
                .withAbilityName(TabsAbility.class)
                .build();
        startTabsAbilityIntent.setOperation(operation);
        PageSlider pageSlider = (PageSlider) findComponentById(ResourceTable.Id_view_pager);
        MaterialTabs materialTabs = (MaterialTabs) findComponentById(ResourceTable.Id_material_tabs);
        ActionBar actionBar = (ActionBar) findComponentById(ResourceTable.Id_actionbar);
        actionBar.addClickListener((clickType, position) -> {
            if (clickType == ActionBar.ActionBarType.LEFT_ICON) {
                startAbility(startTabsAbilityIntent);
            } else if (clickType == ActionBar.ActionBarType.RIGHT_ICON) {
                if (position == 0) {
                    showAdDialog();
                } else if (position == 1) {
                    showInfoDialog();
                } else if (position == 2) {
                    startAbility(startTabsAbilityIntent);
                }
            }
        });
        ViewPagerAdapter adapter = new ViewPagerAdapter(this, mFragments);
        pageSlider.setProvider(adapter);
        materialTabs.setViewPager(pageSlider);
        pageSlider.setPageMargin(AttrHelper.vp2px(4, getContext()));
        pageSlider.setCurrentPage(0);
    }

    private void showInfoDialog() {
        CustomDialog.init(getContext())
                .setLayoutId(ResourceTable.Layout_dialog_info_layout, ConstandCodes.COMMONTYPE)
                .setViewConvertListener((holder, dialog) -> {
                    Text tv_content = holder.getView(ResourceTable.Id_tv_content);
                    tv_content.setText("Reset everything to default?");
                    Text tv_no = holder.getView(ResourceTable.Id_tv_no);
                    tv_no.setClickedListener(component -> dialog.hide());
                    Text tv_yes = holder.getView(ResourceTable.Id_tv_yes);
                    tv_yes.setClickedListener(component -> {
                        resetDefaults();
                        dialog.hide();
                    });
                })
                .setTransparent(true)
                .show();
    }

    private void showAdDialog() {
        CustomDialog.init(getContext()).setLayoutId(ResourceTable.Layout_ad_layout, ConstandCodes.COMMONTYPE)
                .setViewConvertListener((holder, dialog) -> {
                    Text github_click = holder.getView(ResourceTable.Id_github_click);
                    github_click.setRichText(createRichText("pizza"));
                    github_click.setClickedListener(component -> {
                        jumpIntent("android.intent.action.VIEW", "http://github.com/pizza");
                        dialog.hide();
                    });

                    Text twitter_click = holder.getView(ResourceTable.Id_twitter_click);
                    twitter_click.setRichText(createRichText("@KarimFrenn"));
                    twitter_click.setClickedListener(component -> {
                        jumpIntent("android.intent.action.VIEW", "http://twitter.com/karimfrenn");
                        dialog.hide();
                    });
                })
                .setSwipeToClose(true)
                .setTransparent(true)
                .show();
    }

    private void jumpIntent(String action, String url) {
        Intent intent = new Intent();
        intent.setAction(action);
        Uri uri = Uri.parse(url);
        intent.setUri(uri);
        startAbility(intent);
    }

    private RichText createRichText(String ss) {
        RichTextBuilder richTextBuilder = new RichTextBuilder(createTextForm());
        richTextBuilder.addText(ss);
        return richTextBuilder.build();
    }

    private TextForm createTextForm() {
        TextForm textForm = new TextForm();
        textForm.setUnderline(true);  // 设置字体 下划线
        textForm.setTextColor(Color.getIntColor("#00BCD5"));
        textForm.setTextSize(35);
        return textForm;
    }

    @Override
    public void onActive() {
        super.onActive();
    }

    @Override
    public void onForeground(Intent intent) {
        super.onForeground(intent);
    }

    /**
     * 状态栏
     *
     * @param ability ability
     */
    public static void initStatus(Ability ability) {
        try {
            int color = ability.getResourceManager().getElement(ResourceTable.Color_mantis).getColor();
            ability.getWindow().setStatusBarColor(color);
        } catch (IOException | NotExistException | WrongTypeException e) {
            e.printStackTrace();
        }
    }

    /**
     * Resets default values of all the settings in both {@link TabsSettingsFragment} and {@link RippleSettingsFragment}.
     */
    private void resetDefaults() {
        for (ResettableFragment f : mFragments) {
            f.setupAndReset();
        }
    }

}
